package com.d3works.apps.contract.batch;

import com.d3works.apps.base.db.Batch;
import com.d3works.apps.base.service.app.AppBaseService;
import com.d3works.apps.contract.db.Contract;
import com.d3works.apps.contract.db.repo.AbstractContractRepository;
import com.d3works.apps.contract.db.repo.ContractRepository;
import com.d3works.apps.contract.service.ContractService;
import com.d3works.db.Query;
import com.d3works.exception.D3worksException;
import com.google.inject.Inject;

public class BatchContractFactoryInvoicing extends BatchContractFactory {

  @Inject
  public BatchContractFactoryInvoicing(
      ContractRepository repository, ContractService service, AppBaseService baseService) {
    super(repository, service, baseService);
  }

  @Override
  public Query<Contract> prepare(Batch batch) {
    return repository
        .all()
        .filter(
            "self.isInvoicingManagement = TRUE "
                + "AND self.currentContractVersion.automaticInvoicing = TRUE "
                + "AND self.invoicingDate <= :date "
                + "AND :batch NOT MEMBER of self.batchSet "
                + "AND self.statusSelect != :statusSelect "
                + "AND self.targetTypeSelect = :targetTypeSelect")
        .bind("date", batch.getContractBatch().getInvoicingDate())
        .bind("batch", batch)
        .bind("targetTypeSelect", batch.getContractBatch().getTargetTypeSelect())
        .bind("statusSelect", AbstractContractRepository.CLOSED_CONTRACT);
  }

  @Override
  public void process(Contract contract) throws D3worksException {
    service.invoicingContract(contract);
  }
}
